package com.tbynet.wordpress.service.provider;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.tbynet.wordpress.model.Options;
import com.tbynet.wordpress.service.OptionService;

public class OptionServiceProvider implements OptionService {
	
	private Options optionDao = new Options().dao();

	@Override
	public boolean save(Object... options) {
		return Db.tx(new IAtom() {
			
			@Override
			public boolean run() throws SQLException {
				for(Object option : options) {
					if(false == ((Options) option).save()) {
						return false;
					}
				}
				return true;
			}
			
		});
	}
	
	@Override
	public boolean update(Object... options) {
		return Db.tx(new IAtom() {
			
			@Override
			public boolean run() throws SQLException {
				for(Object option : options) {
					if(false == ((Options) option).update()) {
						return false;
					}
				}
				return true;
			}
			
		});
	}

	@Override
	public Options getOption(String name) {
		return optionDao.findFirst("select * from wp_options where option_name=? limit 1", name);
	}

	@Override
	public List<Options> getOptions(String... names) {
		List<Options> list = new ArrayList<Options>();
		for(String name : names) {
			Options option = getOption(name);
			if(null != option) {
				list.add(option);
			}
		}
		
		return list;
	}

}
